<template>
  <div class="ganttChart-container">
    <div class="ganttChart-body">
      <div ref="gantt" class="gantt-dom" v-if="isEmpty"></div>
      <div class="empty" v-else>
        <a-empty :image="simpleImage" />
      </div>
      <!-- loading -->
      <div class="loading-warp">
        <a-spin :spinning="loading" />
      </div>
    </div>
  </div>
</template>

<script>
//甘特图
import { Empty } from "ant-design-vue";
import gantt from "dhtmlx-gantt";
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";
import {
  getTableData,
  getTableDataDraft,
  getTableDataHistory,
} from "@/api/progressManage";
export default {
  props: {
    currentVersion: {
      type: Object,
      default: () => {
        return {};
      },
    },
    visible: {
      type: String,
      default: "",
    },
    ganttKeyWord: {
      type: [String, Number],
      default: 1,
    },
  },
  data() {
    return {
      loading: false,
      //甘特图数据
      ganttData: {
        data: [],
        links: [],
      },
      isEmpty: false,
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val == "ganttChart") {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    gantt.templates.task_class = (start, end, task) => {
      let { type } = task;
      return type?.replace(".", "") || "";
    };
  },
  methods: {
    getTableData,
    getTableDataDraft,
    getTableDataHistory,
    //查询table
    getData() {
      this.loading = true;
      let { status } = this.currentVersion;
      let apiUrl = "";
      if (status == 4) {
        //正式
        apiUrl = "getTableData";
      } else if (status == 5) {
        //归档
        apiUrl = "getTableDataHistory";
      } else {
        //草稿
        apiUrl = "getTableDataDraft";
      }
      return new Promise((resolve, reject) => {
        this[apiUrl]({
          showAll: 1,
          versionId: this.currentVersion?.uuid || "",
          nodeType: "scheduleType.01",
          proCode: "",
          orgCode: "",
          startDate: "",
          endDate: "",
          name: "",
          ganttChart: 1,
        })
          .then((res) => {
            let { data } = res;
            this.ganttData.data = data?.chartList ?? [];
            this.ganttData.links = data?.preList ?? [];
            if (this.ganttData.data.length > 0) {
              this.isEmpty = true;
              //甘特图数据
              this.$nextTick(() => {
                this.initGantt();
              });
            } else {
              this.isEmpty = false;
            }
            resolve();
          })
          .catch((_) => {
            this.ganttData.data = [];
            this.ganttData.links = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //初始化-甘特图
    initGantt() {
      // 清空之前的配置
      gantt.clearAll();
      // 设置中文
      gantt.i18n.setLocale("cn");
      //自定义左侧 头部列的内容
      gantt.config.columns = [
        {
          name: "id",
          label: "序号",
          align: "center",
          width: "50",
          template: function(obj) {
            return obj.sortIndex;
          },
        },
        {
          name: "text", //在tasks.data中定义的属性数据，add为例外,add为新增数据项触发gantt新增弹窗，显示为一个加
          label: "任务名称", //标记描述
          tree: true, //相关列应显示树
          width: "200", //宽度，可写max _width min_width
          align: "left", //文字格式
          resize: true, //布尔值，可以拉伸内容宽度
          template: function(obj) {
            return obj.text;
          },
        },
        {
          name: "duration",
          label: "周期",
          align: "center",
          width: "50",
          template: function(obj) {
            return obj.duration;
          },
        },
        {
          name: "start_date",
          label: "计划开始时间",
          align: "center",
          width: "100",
          template: function(obj) {
            return obj.start_date;
          },
        },
        {
          name: "end_date",
          label: "计划完成时间",
          align: "center",
          width: "100",
          template: function(obj) {
            return obj.end_date;
          },
        },
      ];
      //时间轴图表中-日期展示格式
      let { ganttKeyWord = 1 } = this;
      switch (ganttKeyWord) {
        //日视图
        case 1:
          gantt.config.scales = [
            { unit: "year", step: 1, format: "%Y年-%M" },
            { unit: "day", format: "%d" },
          ];
          break;

        //周视图
        case 2:
          gantt.config.scales = [
            { unit: "year", step: 1, format: "%Y年-%M" },
            { unit: "week", format: "第%w周" },
          ];
          break;

        //月视图
        case 3:
          gantt.config.scales = [
            { unit: "year", step: 1, format: "%Y年" },
            { unit: "month", step: 1, format: "%M" },
          ];
          break;

        //季度视图
        case 4:
          gantt.config.scales = [
            { unit: "year", step: 1, format: "%Y年" },
            { unit: "quarter", step: 1, format: quarterLabel },
          ];
          break;
        default:
          break;
      }
      function quarterLabel(date) {
        var month = date.getMonth();
        var q_num;

        if (month >= 9) {
          q_num = "四";
        } else if (month >= 6) {
          q_num = "三";
        } else if (month >= 3) {
          q_num = "二";
        } else {
          q_num = "一";
        }
        return "第" + q_num + "季度";
      }
      // 鼠标经过打开 tooltip 提示
      gantt.plugins({
        tooltip: true,
        // 拖动图
        drag_timeline: true,
      });
      gantt.templates.tooltip_text = function(start, end, task) {
        return `
          <div style="font-weight: 400;font-size: 16px;color: #2B2C30;font-family: Microsoft YaHei;margin-bottom: 10px;"> ${
            task.text
          }</div>
          <div style="font-weight: 400;font-size: 14px;color: #666666;font-family: Microsoft YaHei;margin-bottom: 8px;">计划开始时间：${gantt.templates.tooltip_date_format(
            start
          )}</div>
          <div style="font-weight: 400;font-size: 14px;color: #666666;font-family: Microsoft YaHei;margin-bottom: 8px;">计划结束时间：${gantt.templates.tooltip_date_format(
            end
          )}</div>
           <div style="font-weight: 400;font-size: 14px;color: #666666;font-family: Microsoft YaHei;margin-bottom: 8px;">周期：${
             task.duration
           }</div>
              `;
      };
      //滚动条布局
      gantt.config.scroll_size = 12;
      gantt.config.layout = {
        css: "gantt_container",
        cols: [
          {
            width: 500,
            rows: [
              {
                view: "grid",
                scrollX: "gridScroll",
                scrollable: true,
                scrollY: "scrollVer",
              },
              { view: "scrollbar", id: "gridScroll", group: "horizontal" },
            ],
          },
          { resizer: true, width: 1 },
          {
            rows: [
              { view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer" },
              { view: "scrollbar", id: "scrollHor", group: "horizontal" },
            ],
          },
          { view: "scrollbar", id: "scrollVer" },
        ],
      };
      //取消右边表格进度条显示与拖动
      gantt.config.show_progress = false;
      //用户可以通过拖拽调整行高
      gantt.config.resize_rows = true;
      //时间轴图表中  设置图例高度
      gantt.config.bar_height = 25;
      // 只读模式：打开后不可以操作甘特图
      gantt.config.readonly = true;
      // 初始化甘特图  可以通过ref挂载 或者 id选择器挂载
      gantt.init(this.$refs.gantt);
      // 渲染数据
      gantt.parse(this.ganttData);
      //建议每一次修改配置项调用一次render方法
      gantt.render();
    },
  },
};
</script>

<style lang="less" scoped>
.ganttChart-container {
  width: 100%;
  height: 100%;
  background: #fff;
  box-sizing: border-box;
  padding: 16px;
  overflow: hidden;
  position: relative;
  .ganttChart-body {
    width: 100%;
    height: 100%;
    .gantt-dom {
      height: 100%;
      width: 100%;
    }
    .empty {
      width: 100%;
      height: 100%;
      border: 1px solid #dcdee2;
      position: relative;
      /deep/.ant-empty {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
    }
    .loading-warp {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    /deep/.gantt_task_line {
      &.nodeLevel01 {
        background-color: #5b78f2;
      }
      &.nodeLevel02 {
        background-color: #35b2e1;
      }
      &.nodeLevel03 {
        background-color: #9286ec;
      }
      &.nodeLevel04 {
        background-color: #f07f17;
      }
      &.nodeLevel05 {
        background-color: #f45d5d;
      }
      &.nodeLevel06 {
        background-color: #51bc64;
      }
      &.nodeLevel07 {
        background-color: #d251d4;
      }
      &.nodeLevel08 {
        background-color: #27bead;
      }
    }
  }
}
</style>
<style lang="less">
.gantt_tooltip {
  z-index: 999;
}
</style>
